﻿using System;
using System.IO;
using System.Threading.Tasks;

namespace Miao.ML
{
    public class WinMLDeserializer
    {
        private readonly Parser parser = new Parser();

        private readonly Deanalyzer deanalyzer = new Deanalyzer();

        public bool deserializing { get; private set; }

        public T Deserialize<T>(string winMLString)
        {
            return (T)Deserialize(winMLString, typeof(T));
        }

        public object Deserialize(string winMLString, Type type)
        {
            return deanalyzer.Deanalyze(Deserialize(winMLString), type);
        }

        public async Task<T> DeserializeAsync<T>(string winMLString)
        {
            return (T)(await DeserializeAsync(winMLString, typeof(T)));
        }

        public async Task<object> DeserializeAsync(string winMLString, Type type)
        {
            string winMLString2 = winMLString;
            Type type2 = type;
            if (deserializing)
            {
                throw new Exception("WinMLDeserializer.DeserializeAsync: 正在反序列化中, 不允许重复调用!");
            }

            deserializing = true;
            object result = await Task.Run(() => Deserialize(winMLString2, type2));
            deserializing = false;
            return result;
        }

        public T DeserializeFromFile<T>(string winMLFilePath)
        {
            return Deserialize<T>(File.ReadAllText(winMLFilePath));
        }

        public Task<T> DeserializeFromFileAsync<T>(string winMLFilePath)
        {
            return DeserializeAsync<T>(File.ReadAllText(winMLFilePath));
        }

        public WinMLData Deserialize(string winMLString)
        {
            return parser.ParseData(winMLString);
        }

        public WinMLData DeserializeFromFile(string winMLFilePath)
        {
            return Deserialize(File.ReadAllText(winMLFilePath));
        }

        public void AddDeserializationFunction<T>(Func<string, T> deserializationFunction)
        {
            deanalyzer.AddDeserializationFunction(deserializationFunction);
        }
    }
}
